const app = getApp()
import {
  getProductList
} from "../../../api/productController";
import {
  saleTmplIds
} from "../../../utils/config";
import {
  getCustBaseByUserLoginState
} from "../../../api/custBaseController";
import AUTH from "../../../utils/auth";
import {
  getSwiper
} from "../../../api/banner";

import { getMeSendingOrderCnt } from "../../../api/tradeOrderController";

Component({
  properties: {
    wxlogin: { // 注册成功 首页用来拦截
      type: Boolean,
      value: true
    }
  },
  options: {
    addGlobalClass: true,
  },
  /**
   * 页面的初始数据
   */
  data: {
    wxlogin: true,
    userInfo: '', //用户信息
    sendOrderCnt:0, //待发货的数量，只有user.vipType=20的用户才需要
    noLoginImg: 'https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132',

    cardCur: 0,
    swiperList: [{
      id: 0,
      type: 'image',
      url: '/static/images/banner0.png'
    }, {
      id: 1,
      type: 'image',
      url: '/static/images/banner1.png',
    }, {
      id: 1,
      type: 'image',
      url: '/static/images/banner2.png',
    }],
    navList: [
      {
        id: 1,
        icon: '../../../static/images/icon1-1.png',
        name: '关于我们',
        color: '#FF6600',
        url: '/pages/aboutme/index'  
      },
      {
        id: 2,
        icon: '../../../static/images/icon1-2.png',
        name: '我的订单',
        color: '#00DD99',
        url: '/pages/orders/order-list/index'
      },    
      {
        id: 3,
        icon: '../../../static/images/icon1-3.png',
        name: '我的团队',
        color: '#FFCC66',
        url: '/pages/salesCenter/salesCenter/index'
      },
      {
        id: 4,
        icon: '../../../static/images/icon1-4.png',
        name: '推广码',
        color: '#33CCFF',
        url: '/pages/poster/index'
      },
      // {
      //   id: 5,
      //   icon: '../../../static/images/icon1-5.png',
      //   name: '发货管理',
      //   color: '#00DD99',
      //   url: '/pages/distributionCenter/distributionCenter/index'
      // },
    ],
    goodsRecommend: [], //首页商品
    pageNo: 1, //当前页 
    pageSize: 10, //十条
    searchLoading: true,
    searchLoadingComplete: false,
  },
  

  ready() {
    let self = this;
    console.log('login是异步函数、此时可能获取不到值', app.globalData.plumSession); //wx.login是异步函数、此时可能获取不到值
    if (!app.globalData.plumSession) {
      //未检测到  self.globalData.plumSession
      //创建 app.plumSessionCallback 的回调函数，将plumSession作为函数参数，app.js中检测到函数被创建，
      app.plumSessionCallback = plumSession => {
        console.log('登录信息',plumSession);
        if (plumSession != '') {
          console.log('查询到登录信息');
          self.getCustBaseByUserLoginState()
          self.getProductList()
          self.getMeSendingOrderCnt()
        } else {
          console.log('未查询到登录信息');
          app.wechatSq(self);
        }
      }
    } else {
      self.getCustBaseByUserLoginState()
      self.getProductList()
      self.getMeSendingOrderCnt()
    }
  },
  methods: {
    async getSwiper() {
      let res = await getSwiper()
      let swiperList = res.data
      swiperList.map(item => {
        item.type = 'image'
        item.url = item.image
      })
      this.setData({
        swiperList: swiperList
      })
    },
    /**
     * 根据userLoginState获取当前客户
     */
    async getCustBaseByUserLoginState() {
      console.log("===首页通过sessionId/openid，请求后台redis里的用户信息==")
      let resolve = await getCustBaseByUserLoginState()
      if (resolve.success) {
        wx.setStorageSync('custId', resolve.data.id)
        let userInfo = {
          "nickName": resolve.data.nickname,
          "realName": resolve.data.name,
          "gender": resolve.data.sex,
          "language": resolve.data.language,
          "city": resolve.data.city,
          "province": resolve.data.province,
          "country": resolve.data.country,
          "avatarUrl": resolve.data.headImgUrl,
          "vipType": resolve.data.vipType,
          "vipRank": resolve.data.vipRank,
          "id": resolve.data.id,
          "cloudPoint": resolve.data.cloudPoint,
          "cloudTicket": resolve.data.cloudTicket,
          "commission": resolve.data.commission,
          "typeName": resolve.data.type_name,
        }
        wx.setStorageSync('userInfo', userInfo)
        wx.setStorageSync('userBase', resolve.data)
        this.setData({
          userInfo: userInfo
        })
      }
    },
    /**
     * 分页查询List
     */
    async getProductList() {
      let resolve = await getProductList({
        pageNo: this.data.pageNo,
        pageSize: this.data.pageSize,
        vipType: wx.getStorageSync('userBase').vipType || 0
      })
      if (resolve.data) {
        if (resolve.data.isLastPage) {
          this.setData({
            searchLoadingComplete: false,
            searchLoading: true,
          })
        } else {
          this.setData({
            searchLoadingComplete: true,
            searchLoading: false,
          })
        }
        let goodsRecommend = this.data.goodsRecommend
        this.setData({
          isLastPage: resolve.data.isLastPage,
          goodsRecommend: goodsRecommend.concat(resolve.data.list)
        })
      }
    },

    /**
     * 触底
     */
    ScrollLower() {
      const self = this;
      if (!self.data.isLastPage) {
        self.data.pageNo++
        self.setData({
          pageNo: self.data.pageNo
        })
        this.getProductList()
      }

      // if (self.data.deviceIndex < self.data.devicePages) {
      //   self.setData({
      //     deviceIndex: self.data.deviceIndex + 1, //每次触发触底事件，把deviceIndex+1
      //   });
      // } else if (self.data.deviceIndex == self.data.devicePages) {
      //   self.setData({
      //     searchLoadingComplete: true, //“已加载全部”显示
      //     searchLoading: false, //"正在载入更多"隐藏
      //   });
      // }
    },
    /**
     * 
     */
    goPath(e) {
      let self = this

      let {
        url
      } = e.currentTarget.dataset
      if (url === 'vip') {
        // 微信小程序中是通过triggerEvent来给父组件传递信息的
        self.triggerEvent('clickVIP', {
          PageCur: 'classificationPage'
        })
        return
      }
      wx.navigateTo({
        url: url,
      })
      // 取消向客户发送消息了20240604
      // wx.requestSubscribeMessage({
      //   tmplIds: saleTmplIds,
      //   complete: (res) => {
      //     console.log(res);
      //     AUTH.checkHasLogined().then(isCustId => {
      //       if (!isCustId) {
      //         self.setData({
      //           wxlogin: false,
      //         })
      //       } else {
      //         wx.navigateTo({
      //           url: url,
      //         })
      //       }
      //     })
      //   }
      // })


    },
        /**
     * 获取待发货订单数
     */
    async getMeSendingOrderCnt() {
      let custId = wx.getStorageSync('custId')
      if(custId<1000 && custId >0){
        console.log("发货人员提取发货数，id:"+custId)
        let resolve = await getMeSendingOrderCnt({
          custId: custId
        })
        console.log("查到待发货的订单数："+resolve.data)
        if (resolve.data > 0) {
            this.setData({
              sendOrderCnt: resolve.data,
            })
        }
      }else{
        console.log("不是发货员路过，id："+custId)
      }

      },
  },
  /**
   * 关闭弹窗
   */
  afterAuth(e) {
    this.setData({
      wxlogin: true,
    })
  },



})